<template lang="pug">
div.ci-simplemde
  textarea(ref="ci-editor")
</template>

<script>
/**
 * @fileoverview CISimpleMDE
 * @author burning (www.cafeinit.com)
 * @version 2017.04.24
 */
import SimpleMDE from 'simplemde'

export default {
  name: 'ci-simplemde',

  props: {
    value: {
      type: String,
      default: ''
    },

    config: {
      type: Object,
      default() {
        return {}
      }
    }
  },

  watch: {
    value(val) {
      if (val == this.simplemde.value()) {
        return
      }
      else {
        this.simplemde.value(val)
      }
    }
  },

  mounted() {
    this.initialize()
  },

  destroyed() {
    this.simplemde = null
  },

  methods: {
    initialize() {
      let toolbar = [
        'bold', 'italic',
        'heading-1', 'heading-2', 'heading-3', '|',
        'quote', 'unordered-list', 'ordered-list', '|',
        'link', 'image', 'preview', '|'
      ]
      toolbar.push({
        name: 'custom',
        className: 'fa fa-star',
        title: 'Custom Button',
        action(editor) {
          console.log('custom', editor)
          let output = ''
          let cm = editor.codemirror
          let selectedText = cm.getSelection() || ''

          output = '!!' + selectedText + '!!'
          cm.replaceSelection(output)
          cm.focus()
        }
      })
      let config = {
        toolbar: toolbar
      }
      Object.assign(config, this.config)
      config.element = this.$refs['ci-editor']
      config.initialValue = this.value

      this.simplemde = new SimpleMDE(config)

      // ...

      this.bindEvents()
    },

    bindEvents() {
      this.simplemde.codemirror.on('change', () => {
        this.$emit('input', this.simplemde.value())
      })
    }
  }
}
</script>
